package device

import (
	"bytes"
	"context"
	"encoding/hex"
	"fpga-vboard/pins"

	"github.com/wailsapp/wails/v2/pkg/runtime"
)

const (
	Leds_pin    = "leds_input"
	Leds_Number = 20
)

func init() {
	config := &LedsConfig{
		DeviceInfo: DeviceInfo{
			Id:   Leds_DEFAULT,
			Type: Leds,
			InputPins: []*pins.PinDef{
				{
					Name:      Leds_pin,
					BitSize:   Leds_Number,
					Direction: pins.PinDirectionInput,
				},
			},
			Name:       "Led lights",
			OutputPins: nil,
			IsOptional: true,
			Enable:     false,
		},
		LedNumbers:  Leds_Number,
		Color:       "",
		LighingMode: "high",
	}
	RegisterDev(config)
}

type LedLights struct {
	*DeviceBase
	lastValues []byte
}

func NewLedLights(config *LedsConfig) *LedLights {
	return &LedLights{
		DeviceBase: &DeviceBase{
			Config: config,
		},
		lastValues: make([]byte, (Leds_Number+7)/8),
	}
}

func (l *LedLights) Run(ctx context.Context) {
	values := l.GetPinBytes(Leds_pin)
	if !bytes.Equal(l.lastValues, values) {
		copy(l.lastValues, values)
		runtime.EventsEmit(ctx, "ledsupdate", hex.EncodeToString(values))
	}
}
